package com.rtline.business.handler;

import com.rtline.business.annotation.RateLimit;
import com.rtline.business.ratelimit.FixedWindowRateLimitStrategy;
import com.rtline.business.ratelimit.RateLimitStrategy;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class RateLimitInterceptor implements HandlerInterceptor {
    private final RateLimitStrategy rateLimitStrategy = new FixedWindowRateLimitStrategy();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RateLimit rateLimit = handlerMethod.getMethodAnnotation(RateLimit.class);
            if (rateLimit != null) {
                String resource = rateLimit.resource();
                if (resource.isEmpty()) {
                    resource = handlerMethod.getMethod().getName();
                }

                if (!rateLimitStrategy.isAllowed(resource, rateLimit.limit(), rateLimit.period())) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    response.getWriter().write(rateLimit.message());
                    return false;
                }
            }
        }
        return true;
    }
}
